<?php
/**
 * Created by PhpStorm.
 * User: chenjunjie
 * Date: 2020/9/2
 * Time: 3:33 PM
 */

namespace App\Controller\Api;


use App\Controller\Auth\Controller;
use App\Model\Saas;
use App\Model\XApiCompany;
use App\Model\XApiUser;
use App\Model\XApiUserCompany;
use App\Model\XApiUserSaasTmp;
use App\Model\XSaasBlacklist;
use App\Model\XSaasBlacklistSms;
use App\Model\XUnionCompany;
use Hyperf\Database\Model\ModelNotFoundException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Upload\UploadedFile;
use Hyperf\Logger\LoggerFactory;
use League\Flysystem\Filesystem;

class FaceDeviceController extends Controller
{

    /**
     *
     * @Inject
     * @var Filesystem
     */
    private $filesystem;
    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;
    /**
     * @Inject
     * @var \App\Service\SmsService
     */
    private $smsService;

    private $host;
    private $qrCodeKey = "70586d875cea742d";
    private $blackType = [1=>"场所",2=>"协会"];
    private $userType = [1=>"员工",2=>"访客"];
    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->host = env('JAVA_API');
        $this->logger = $loggerFactory->get('log', 'default');
    }

    public function updatePerson(){
        $url = $this->updateOss($this->request->file("faceFile"));
        $this->logger->info("请求日志",$this->request->all());
        $this->logger->info('上传成功'.$url);
        return $this->successFootJsonResponse(null,'保存人员信息成功');
    }




    public function downPersonListByDeviceMac(){
        $updateTime = date('Y-m-d H:i:s',ceil($this->request->input("timeStamp")/1000));
        $mac = $this->request->input("mac");
        $size = $this->request->input("size");
        $companyId = $this->getCompanyId($mac);
        $this->logger->info("调用人员列表接口 场所Id".$companyId." MAC:".$mac);
        return $this->successFootJsonResponse($this->getUserList($companyId,$size,$updateTime));
    }

    public function downPersonCountByDeviceMac(){
        $updateTime = date('Y-m-d H:i:s',ceil($this->request->input("timeStamp")/1000));
        $mac = $this->request->input("mac");
        $companyId = $this->getCompanyId($mac);


        $this->logger->info("调用人员列表人数接口 场所Id".$companyId." MAC:".$mac);
        return $this->successFootJsonResponse($this->getUserCount($companyId,$updateTime));
    }




    public function uploadDeviceFace(){

        $this->logger->info("请求日志",$this->request->all());
        $identifyNumber = $this->request->input("identifyNumber");
        $mac = $this->request->input("mac");
        $companyId = $this->getCompanyId($mac);

        $this->logger->info("调用重置人脸接口 场所Id".$companyId." MAC:".$mac);

        $url = $this->updateOss($this->request->file("faceFile"));

        if( strlen($identifyNumber) > 10) {
            $identifyNumber = $this->getUserIdNew($identifyNumber);
        }


        $userCompany = $this->checkUserCompany($identifyNumber,$companyId);
        if(!$userCompany){
            return $this->successFootJsonResponse(null,"用户未入职该场所",10100);
        }

        $postFields = [
            'mac' => $mac,
            'userId' => $identifyNumber,
            'companyId'=>$companyId,
            'pic'=>$url,
        ];

        $data = $this->curlPost($this->host.'/api/company/machineResetInfo',$postFields);

        $data = json_decode( json_decode($data)->resText);
//        var_dump($data);

        $message = $data->errorMsg;
//        if ($data->code == 0){
//            $message = $data->result->name;
//        }

        return $this->response->json([
            'code' => $data->code,
            'data' => $data->success,
            'message' => $message
        ]);


    }




    public function uploadFingerPrint(){

        $this->logger->info("请求日志",$this->request->all());
        $identifyNumber = $this->request->input("identifyNumber");
        $mac = $this->request->input("mac");
        $companyId = $this->getCompanyId($mac);

        $this->logger->info("调用上传指纹 场所Id".$companyId." MAC:".$mac);

        $i = [1,2];
        $finger = [];
        foreach ($i as $item){
            if ($this->request->input("finger".$item)){
                $finger['finger'.$item] = $this->updateOss($this->request->input("finger".$item));
            }
        }
        if (empty($finger)){
            return $this->successFootJsonResponse(null,"请上传指纹",10039);
        }

        if( strlen($identifyNumber) > 10) {
            $identifyNumber = $this->getUserIdNew($identifyNumber);
        }

        $userCompany = $this->checkUserCompany($identifyNumber,$companyId);
        if(!$userCompany){
            return $this->successFootJsonResponse(null,"用户未入职该场所",10100);
        }
        $oldUserInfo = (array)json_decode($userCompany->user_company_info);
        $userInfo = array_merge($oldUserInfo,$finger);
        $userCompany->user_company_info = json_encode($userInfo,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        $userCompany->save();
        return $this->successFootJsonResponse(null,'场所指纹上传成功');
    }

    /**
     * 获取上传的考勤日志
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function uploadRecordFromApp(){
//        var_dump($this->request->file("file"));
        $this->logger->info("请求日志",$this->request->all());
        $url = $this->updateOss($this->request->file("file"));
//        Log::info('上传成功'.$url);


        $user_id = $this->request->input("identifyNumber",0);
        $identifyNumber = $this->decodeId( $this->request->input("identifyNumber") );

        try{
            $user = XApiUser::findOrFail($user_id);
            $idCard = $user->cert_num;
        }catch (ModelNotFoundException $exception){
            $idCard = 0;
        }
        $mac = $this->request->input("mac");
        $companyId = $this->getCompanyId($mac);
        $saasUser = new SaasUser();
        $saasUser->id_card = $idCard;
        $saasUser->user_name = $this->request->input("userName");
        $saasUser->mac = $mac;
        $saasUser->user_type = $this->request->input("type");
        $saasUser->company_id = $companyId;
        $saasUser->temperature = $this->request->input("temperature");
//        $saasUser->auth_result = $this->request->input("score");
        $saasUser->score = $this->request->input("score");
        $saasUser->verify_time = $this->request->input("verifyTime");
        $saasUser->img = $url;
        $saasUser->attendance_type = $this->request->input("attendanceType");
        $saasUser->user_id = (int)$user_id;




        if ($this->request->input("blackId") > 0){
            $saasBlack = $this->blackAction($this->request->input("blackId"),$companyId);
            if ($saasBlack->id > 0){
                $saasUser->blacklist_type = $saasBlack->type;
                $saasUser->user_type = $saasBlack->user_type;
                $saasUser->blacklist_reason = $saasBlack->reason;
                $saasUser->union_id = $saasBlack->union_id;
                $saasUser->user_name = $saasBlack->user_name;
                $saasUser->id_card = $saasBlack->id_card;
                $saasUser->login_name = $saasBlack->login_name;
            }
        }
        $saasUser->save();

        return $this->successFootJsonResponse(null,'上传日志成功');
    }



    /**
     * 考勤接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dailyAttendance(){
//        var_dump($this->request->file("file"));

        $this->logger->info("请求日志",$this->request->all());
        $identifyNumber = $this->request->input("identifyNumber");
        $mac = $this->request->input("mac");
        $companyId = $this->getCompanyId($mac);

        $userId = $this->getUserId($identifyNumber);
        if( strlen($userId) > 10){
            $userId = $this->getUserIdNew($userId);
        }
        $postFields = [
            'mac' => $mac,
            'userId' => $userId,
//            'userCompanyId' => $this->getUserCompanyId($userId,$companyId),
            'companyId'=>$companyId,
            'defaultCompanyId'=>$companyId,
            'latitude' => $this->request->input("temperature"),
            'longitude' => $this->request->input("temperature"),
        ];

        $data = $this->curlPost($this->host.'/api/attendance/attendanceMachine',$postFields);

        $data = json_decode( json_decode($data)->resText);
//        var_dump($data);

        $message = $data->errorMsg;
        if ($data->code == 0){
            $message = $data->result->name;
        }

        return $this->response->json([
            'code' => $data->code,
            'data' => $data->success,
            'message' => $message
        ]);

    }


    /**
     * 获取考勤机所配置的权限
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function getDevicePermission(){
        $mac = $this->request->input("mac");
        $version = $this->request->input("version");

        $this->logger->info("调用获取考勤机权限接口 MAC:".$mac);
        try{
            $saas = Saas::where('mac',$mac)->where('is_delete',0)->firstOrFail();

            if ($version == 2){
                $saasInfo = [
                    'permission'=>$saas->permission,
                    'deviceType'=>$saas->device_type,
                    'use'=>$saas->use_type,
                    'status' => 0
                ];


                if ($saas->is_delete == 1){
                    $saasInfo['status'] = 2;
                    $saasInfo['permission'] = [1];
                }
                return $this->successFootJsonResponse($saasInfo,'获取权限成功 1考勤2人员3建档4日志5设置6黑名单菜单');
            }
            return $this->successFootJsonResponse($saas->permission,'获取权限成功 1考勤2人员3建档4日志5设置6黑名单菜单');

        }catch (ModelNotFoundException $exception){
            return $this->successFootJsonResponse(null,'设备不存在');
        }
    }


    public function downBlacklistByDeviceMac(){
        $updateTime = date('Y-m-d H:i:s',ceil($this->request->input("timeStamp")/1000));
        $mac = $this->request->input("mac");
        $companyId = $this->getCompanyId($mac);

        $this->logger->info("调用获取黑名单人员列表接口 场所Id".$companyId." MAC:".$mac);
        $unionId = $this->getUnionId($companyId);
        if ($unionId  > 0){

            $data = SaasBlacklist::where(function ($query) use ($companyId,$unionId) {
                $query->where('company_id',$companyId)
                    ->orWhere('union_id',$unionId);
            })->where('edit_time','>=',$updateTime)->get();
        } else {
            $data = SaasBlacklist::where('company_id',$companyId)->where('edit_time','>=',$updateTime)->get();
        }

        return $this->successFootJsonResponse($this->transBlacklistData($data));
    }


    public function generateQrCodeByOnBoardingInfo(){

        $this->logger->info("请求日志",$this->request->all());
        try{
            ApiUser::where('cert_num',$this->request->input("identifyNumber"))->where('status',1)->firstOrFail();
            return $this->successFootJsonResponse(null,"该用户信息已存在",10078);
        }catch (ModelNotFoundException $exception){
        }

        $companyId = $this->getCompanyId($this->request->input("mac"));
        try{
            SaasBlacklist::where('id_card',$this->request->input("identifyNumber"))->where('company_id',$companyId)->where('is_delete',0)->firstOrFail();
            return $this->successFootJsonResponse(null,"该用户为黑名单用户",10079);
        }catch (ModelNotFoundException $exception){

        }

        if ($this->request->input("compareResult") != "1"){
            return $this->successFootJsonResponse(null,"人脸比对失败",10070);
        }


        $this->logger->info("调用获取入职二维码接口 场所Id".$companyId." MAC:".$this->request->input("mac"));
        $facePicUrl = $this->updateOss($this->request->file("facePic"));

        $i = [1,2];
        $finger = [];
        foreach ($i as $item){

            if ($this->request->input("finger".$item)){
                $finger['finger'.$item] = $this->updateOss($this->request->input("finger".$item));
            }
        }

        $idCardFrontPicUrl = $this->updateOss($this->request->input("idCardFrontPic"));
        $user = new ApiUserSaasTmp();
        $user->company_id = $companyId;
        $user->cert_num = $this->request->input("identifyNumber");
        $user->user_name = $this->request->input("userName");
        $user->ethnic_group = $this->request->input("ethnicGroup");
        $user->id_card_front_pic = $idCardFrontPicUrl;
        $user->face_pic = $facePicUrl;
        if (!empty($finger))
            $user->finger_pics = json_encode($finger,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        $user->face_device_pic = $facePicUrl;
        $user->regis_address = $this->request->file("address");
        $user->address = $this->request->file("address");
        $user->sex = $this->request->file("sex");
        $user->compare_result = $this->request->input("compare_result");
        $user->id_card_expiry = $this->request->input("idCardExpiry");
        $user->id_card_expiry_type = $this->request->input("idCardExpiryType");
        $user->issuing_authority = $this->request->input("issuingAuthority");
        $user->save();



        $data = [
            'expiresDate' => date('Y-m-d H:i:s',time()+60*15),
            'recordId'=>$user->id
        ];


        $company = ApiCompany::find($companyId);
        $resp = [
            'encryptData' => $this->des_ecb_encrypt(json_encode($data,JSON_UNESCAPED_UNICODE),$this->qrCodeKey),
            'queryId' => $user->id,
            'companyName' => $company->nickname
        ];
        return $this->successFootJsonResponse(
            $resp,
            '信息上传成功'
        );

    }


    public function getQrCodeStatus(){

        $this->logger->info("请求日志",$this->request->all());
        $user = XApiUserSaasTmp::find($this->request->input("queryId"));

        return $this->successFootJsonResponse(['status'=>$user->status],'状态查询成功');
    }

    /**
     * 获取考勤机对应场所id
     * @param $mac
     * @return int
     */
    private function getCompanyId($mac){
        try{
            $saas = Saas::where('mac',$mac)->where('is_delete',0)->firstOrFail();
        }catch (ModelNotFoundException $exception){
            return 0;
        }
        return $saas->company_id;
    }

    /**
     * 获取符合条件用户列表
     * @param $mac
     * @param $size
     * @param $updateTime
     * @return array
     */
    private function getUserList($mac,$size,$updateTime){

//        return $this->transUserData(DB::table('x_api_user')->where('x_api_user_company.company_id',$mac)
//            ->where('x_api_user.update_time','>',$updateTime)
//            ->leftJoin('x_api_user_company', 'x_api_user.id', '=', 'x_api_user_company.user_id')
//            ->orderBy('x_api_user.update_time','asc')
//            ->take($size)
//            ->get());

        $data = XApiUserCompany::where('company_id',$mac)
            ->leftJoin('x_api_user', 'x_api_user.id', '=', 'x_api_user_company.user_id')
//            ->where(function ($query) use ($updateTime) {
//                $query->where('x_api_user.update_time','>',$updateTime)
//                    ->orWhere('x_api_user_company.update_date','>',$updateTime);
//            })
            ->where('x_api_user_company.update_date','>=',$updateTime)
//            ->where('x_api_user_company.status','!=',2)
//            ->where('x_api_user_company.flag',0)
            ->whereNotNull('x_api_user.user_name')
            ->orderBy('x_api_user_company.update_date','asc')
            ->select('x_api_user_company.update_date',
                'x_api_user_company.creat_date',
                'x_api_user_company.status',
                'x_api_user_company.disabled',
                'x_api_user_company.user_company_info',
                'x_api_user_company.flag',
                'x_api_user.update_time',
                'x_api_user.login_name',
                'x_api_user.cert_num',
                'x_api_user.user_name',
                'x_api_user.id as user_id',
                'x_api_user.face_device_pic',
                'x_api_user.update_time')
            ->take($size)
            ->get();

        return $this->transUserData($data);

    }

    /**
     * 获取符合条件用户数
     * @param $mac
     * @param $updateTime
     * @return mixed
     */
    private function getUserCount($mac,$updateTime){

//        return DB::table('x_api_user')->where('x_api_user_company.company_id',$mac)
//            ->where('x_api_user.update_time','>',$updateTime)
//            ->leftJoin('x_api_user_company', 'x_api_user.id', '=', 'x_api_user_company.user_id')
//            ->orderBy('x_api_user.update_time','asc')
//            ->count();

        $data = ApiUserCompany::where('company_id',$mac)
            ->leftJoin('x_api_user', 'x_api_user.id', '=', 'x_api_user_company.user_id')
//            ->where(function ($query) use ($updateTime) {
//                $query->where('x_api_user.update_time','>',$updateTime)
//                    ->orWhere('x_api_user_company.update_date','>',$updateTime);
//            })

            ->where('x_api_user_company.update_date','>=',$updateTime)
//            ->where('x_api_user_company.status','!=',2)
//            ->where('x_api_user_company.flag',0)
//            ->whereNotIn('x_api_user_company.disabled',[1,2])
            ->count();

        return $data;
    }

    /**
     * 转换输出格式
     * @param $data
     * @return array
     */
    private function transUserData($data){
//        var_dump($data);
        $newData = [];
        foreach ($data as $item){

            $updateTime = $item->update_date;
//            if ($item->update_date < $item->update_time ){
//                $updateTime = $item->update_time;
//            }
            $status = $item->status;
            if( in_array($item->disabled,[1,2]) or $item->flag == 1){
                $status = 2;
            }

            $fingerInfo = (array)json_decode($item->user_company_info);

            $startTime = date('Y-m-d H:i:s',strtotime( $item->creat_date ));
            $identifyNumber = $this->encodeId( $item->user_id );
            $newData[] = [
                'userName' => $item->user_name,
                'userType' => 1,
                'userPhone' => $this->desensitize( $item->login_name ,3,4),
                'identifyNumber' => $identifyNumber,
                'startTime' => $startTime,
                'invalidTime' => $startTime,
                'updateTime' => strtotime( $updateTime )*1000,
                'facePicture' => $this->signUrl( $item->face_device_pic),
                'facePicturePath' => $item->face_device_pic,
                'faceFeature' => 111,
                'finger1' => @$fingerInfo['finger1']?$this->signUrl($fingerInfo['finger1']):null,
                'finger2' => @$fingerInfo['finger2']?$this->signUrl($fingerInfo['finger2']):null,
                'maskFaceFeature' => 222,
                'status' => $status,
            ];
        }

//        $newData  = $this->mpSort($newData,'updateTime');
        return $newData;
    }



    /**
     * 转换输出格式
     * @param $data
     * @return array
     */
    private function transBlacklistData($data){
//        var_dump($data);
        $newData = [];
        foreach ($data as $item){
            $status = $item->is_delete;
            if ($item->is_delete == 1){
                $status = 2;
            }
            $updateTime = $item->edit_time;
            $newData[] = [
                'userName' => $item->user_name,
                'userType' => $item->user_type,
                'userPhone' => $this->desensitize( $item->login_name ,3,4),
                'identifyNumber' => $this->encodeId( $item->user_id ),
                'blackId' => $item->id,
                'updateTime' => strtotime( $updateTime )*1000,
                'facePicture' => $this->signUrl( $item->face_pic),
                'status' => $status,
                'reason' => $item->reason,
            ];
        }

//        $newData  = $this->mpSort($newData,'updateTime');
        return $newData;
    }


    /**
     *
     * 上传oss
     * @param $file
     * @param string $filePath
     * @return bool
     */
    private function updateOss(UploadedFile $file,$filePath = "xinyu/idCard"){
//        $disk = Storage::disk("oss");
//
//        //将图片上传到OSS中，并返回图片路径信息 值如:avatar/WsH9mBklpAQUBQB4mL.jpeg
//        $path = $disk->put($filePath."/saas/".date('Ymd'), $file);
//
//        //由于图片不在本地，所以我们应该获取图片的完整路径，
//        //值如：https://test.oss-cn-hongkong.aliyuncs.com/avatar/8GdIcz1NaCZ.jpeg
//        return $path;


        $url = $filePath."/saas/".date('Ymd')."/".$file->getClientFilename();
        $stream = fopen($file->getRealPath(), 'r+');
        $this->filesystem->writeStream(
            $url,
            $stream
        );
        fclose($stream);

        return $url;

    }

    /**
     * 生成私有图下载链接
     * @param $file
     * @return string
     */
    public function signUrl($file){
        if ('' == $file){
            return $file;
        }
        if ( substr($file , 0 , 1) == '/') {
            $file = substr($file,1);
        }

        $ak=env("OSS_ACCESS_ID");

        $sk=env("OSS_ACCESS_SECRET");

        $domain="https://image.hzxyle.com/";//图片域名或Bucket域名

        $expire=time()+3600;

        $bucketname="xrecreation";

//        $file="xinyu/idCard/887513/facePic_XLV28I1584800431755.jpg";//或者"mulu/1.jpg@!样式名"  或者 mulu/1.jpg”

        $StringToSign="GET\n\n\n".$expire."\n/".$bucketname."/".$file;

        $Sign=base64_encode(hash_hmac("sha1",$StringToSign,$sk,true));

        $url=$domain.urlencode($file)."?OSSAccessKeyId=".$ak."&Expires=".$expire."&Signature=".urlencode($Sign);

        return $url;
    }

    private function getUserId($idCard){

        return $this->decodeId($idCard);
//        $idCard = $this->decodeId($idCard);
//        try{
//            $user = ApiUser::where('cert_num',$idCard)->firstOrFail();
//        }catch (ModelNotFoundException $exception){
//            return 0;
//        }
//        return $user->id;
    }
    private function getUserIdNew($idCard){

        // return $this->decodeId($idCard);
        //$idCard = $this->decodeId($idCard);
        try{
            $user = ApiUser::where('cert_num',$idCard)->where('status',1)->where('flag',0)->firstOrFail();
        }catch (ModelNotFoundException $exception){
            return 0;
        }
        return $user->id;
    }
    private function getUserCompanyId($userId,$companyId){
        try{
            $user = ApiUserCompany::where('user_id',$userId)
                ->where('company_id',$companyId)
                ->whereIn('status',[0,1])
                ->whereNotIn('disabled',[1,2])
                ->where('flag',0)
                ->firstOrFail();
        }catch (ModelNotFoundException $exception){
            return 0;
        }
        return $user->id;
    }

    /**
     * 通过CURL发送HTTP请求
     * @param string $url //请求URL
     * @param array $postFields //请求参数
     * @return mixed
     */
    public function curlPost($url,$postFields)
    {

        $this->logger->info('调用Java接口 : '.$url,$postFields);
        $postFields = http_build_query($postFields);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $result = curl_exec($ch);
        curl_close($ch);
        $this->logger->info('Java返回'.$result);
        return $result;
    }
    function http_post_json($url, $jsonStr)
    {

        $this->logger->info('url:'.$url);
        $this->logger->info('p:'.$jsonStr);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $response;
    }

    function mpSort($arr,$key){
        for($i=0;$i<count($arr);$i++){
            for($j=$i;$j<count($arr);$j++){
                if($arr[$i][$key]>$arr[$j][$key]){
                    $temp=$arr[$i];
                    $arr[$i]=$arr[$j];
                    $arr[$j]=$temp;
                }
            }
        }
        return $arr;
    }


    /**
     * des-ecb加密
     * @param string  $data 要被加密的数据
     * @param string  $key 加密密钥(64位的字符串)
     * @return string
     */
    function des_ecb_encrypt($data, $key){
        return openssl_encrypt ($data, 'des-ecb', $key);
    }

    /**
     * des-ecb解密
     * @param string  $data 加密数据
     * @param string  $key 加密密钥
     * @return string
     */
    function des_ecb_decrypt ($data, $key){
        return openssl_decrypt ($data, 'des-ecb', $key);
    }

    /**
     * 数据脱敏
     * @param $string
     * @param int $start
     * @param int $length
     * @param string $re
     * @return string
     */
    function desensitize($string, $start = 0, $length = 0, $re = '0'){
//        if(empty($string) || empty($length) || empty($re)) return $string;
        $end = $start + $length;
        $strlen = mb_strlen($string);
        $str_arr = array();
        for($i=0; $i<$strlen; $i++) {
            if($i>=$start && $i<$end)
                $str_arr[] = $re;
            else
                $str_arr[] = mb_substr($string, $i, 1);
        }
        return implode('',$str_arr);
    }

    function encodeId($userId){
        return $userId;
//        $strId = (string)$userId;
//        $len = mb_strlen($strId);
//        $newId = "";
//        for ($i=1;$i<=$len;$i++){
//            $num = rand(0,9);
//            if ($i == 1){
//                $num = rand(1,9);
//            }
//            if ($i%2==0){
//                $newId .= $num.$strId[$i-1];
//            }else{
//                $newId .= $strId[$i-1].$num;
//            }
//        }
//
//        return (int)$newId;
    }
    function decodeId($userId){
        return $userId;
//        $strId = (string)$userId;
//        $len = mb_strlen($strId);
//        $newId = "";
//        for ($i=1;$i<=$len/2;$i++){
//            $strKey1 = $i*2-2;
//            $strKey2 = $i*2-1;
//            if ($i%2==0){
//                $newId .= $strId[$strKey2];
//            }else{
//                $newId .= $strId[$strKey1];
//            }
//        }
//
//        return (int)$newId;
    }

    /**
     * @param $blackId
     * @param $companyId
     * @return XSaasBlacklist
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function blackAction($blackId,$companyId):XSaasBlacklist
    {
        try {
            $blackUser = XSaasBlacklist::where('id',$blackId)->where('is_delete',0)->firstOrFail();
            $numbers = $this->getSmsMobiles($blackUser,$companyId);
            if (false !== $numbers)
                $this->smsService->send($numbers,$this->getSmsTemplate($blackUser,$companyId),$blackUser->id,$companyId);
            return $blackUser;
        }catch (ModelNotFoundException $exception) {
            return new XSaasBlacklist();
        }
    }
    private function getSmsTemplate(XSaasBlacklist $blackUser,int $companyId){
        $company = XApiCompany::find($companyId);
        return json_encode([
            'name'=>$blackUser->user_name,
            'time'=>date("Y-m-d H:i:s"),
            'company'=>$company->nickname,
            'type'=>$this->blackType[$blackUser->type].$this->userType[$blackUser->user_type]
        ],JSON_UNESCAPED_UNICODE);
    }

    private function getSmsMobiles(XSaasBlacklist $blacklist,int $companyId) {
        $smsNumbers = [];
        if ($blacklist->union_id){

            try{
                $unionSms = XSaasBlacklistSms::where("union_id",$blacklist->union_id)->where("is_delete",0)->firstOrFail();
                $smsNumbers = array_merge($smsNumbers, explode(",",$unionSms->numbers));
                try{
                    $companySms = XSaasBlacklistSms::where("company_id",$companyId)->where("union_blacklist",1)->where("is_delete",0)->firstOrFail();
                    $smsNumbers = array_merge($smsNumbers, explode(",",$companySms->numbers));
                }catch (ModelNotFoundException $exception){

                }
                return implode(",",$smsNumbers);
            }catch (ModelNotFoundException $exception){
                return false;
            }

        }else{
            try{
                $sms = XSaasBlacklistSms::findOrFail($blacklist->blacklist_sms_id);
                return $sms->numbers;
            }catch (ModelNotFoundException $e){
                return false;
            }
        }




    }
    public function checkUserCompany($userId,$companyId){
        try{
            return XApiUserCompany::where('user_id',$userId)->where('company_id',$companyId)->firstOrFail();
        }catch (ModelNotFoundException $exception){
            return false;
        }
    }
    private function getUnionId($companyId){
        try{
            $unionCompany = XUnionCompany::where('company_id',$companyId)->firstOrFail();
            return $unionCompany->union_id;
        }catch (ModelNotFoundException $exception){
            return 0;
        }
    }

}